# -*- coding: UTF-8 -*-
from selenium import webdriver
from bean.hot_new import HotNew
from typing import List
from selenium.webdriver.common.by import By
from news_platform.plat.web_platform import WebPlatform
import traceback


base_url = "https://www.baidu.com/s?word="


class BaiDu(WebPlatform):

    def __init__(self):
        self.name = "百度热搜"

    def query_hot_news(self):
        result: List[HotNew] = []
        chrome_options = webdriver.ChromeOptions()
        chrome_options.add_argument("--headless")
        chrome_options.add_argument("--disable-gpu")
        chrome_options.add_argument("--start-maximized")
        chrome_options.add_argument("--no-sandbox")
        browser = webdriver.Chrome(options=chrome_options)
        # noinspection PyBroadException
        try:
            browser.get("https://top.baidu.com/board?tab=realtime")
            browser.implicitly_wait(10)
            news_div_list = browser.find_elements(By.CLASS_NAME, "content_1YWBm")
            if len(news_div_list) == 0:
                return
            serial_no = 0
            for news_div in news_div_list:
                news_a_list = news_div.find_elements(By.TAG_NAME, 'a')
                if len(news_a_list) == 0:
                    continue
                news_title_div_list = news_div.find_elements(By.CLASS_NAME, 'c-single-text-ellipsis')
                if len(news_title_div_list) == 0:
                    continue
                news_excerpt_div_list = news_div.find_elements(By.CLASS_NAME, 'large_nSuFU')
                if len(news_excerpt_div_list) == 0:
                    continue
                excerpt = news_excerpt_div_list[0].get_property("innerText").replace('查看更多>', '')
                serial_no = serial_no + 1
                news_title_div = news_title_div_list[0]
                title = news_title_div.text
                news_a = news_a_list[0]
                link = news_a.get_attribute('href')
                result.append(HotNew(serial_no, title, link, "1", "热搜指数 ", excerpt))

        except Exception as e:
            print(e)
            print(traceback.format_exc())
        browser.quit()
        return result
